import { Upload, Button, Select, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { useState } from 'react';

const FileConverter = () => {
  const [format, setFormat] = useState('pdf');

  const handleUpload = async (file: File) => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('format', format);

    try {
      const response = await fetch('http://localhost:3001/api/convert', {
        method: 'POST',
        body: formData,
      });
      
      if (response.ok) {
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `converted.${format}`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
        message.success('文件转换成功！');
      } else {
        message.error('文件转换失败，请重试！');
      }
    } catch (error) {
      message.error('文件转换失败，请重试！');
    }
  };

  return (
    <div style={{ textAlign: 'center', padding: '20px' }}>
      <h2>文件转换</h2>
      <div style={{ marginBottom: '20px' }}>
        <Select
          defaultValue={format}
          style={{ width: 120, marginRight: '20px' }}
          onChange={setFormat}
          options={[
            { value: 'pdf', label: 'PDF' },
            { value: 'doc', label: 'DOC' },
            { value: 'docx', label: 'DOCX' },
            { value: 'txt', label: 'TXT' },
          ]}
        />
        <Upload
          customRequest={({ file }) => handleUpload(file as File)}
          showUploadList={false}
        >
          <Button icon={<UploadOutlined />}>选择文件</Button>
        </Upload>
      </div>
      <p>支持多种文件格式转换，文件大小限制为50MB</p>
    </div>
  );
};

export default FileConverter; 